﻿using System;
using System.DirectoryServices;

namespace Hx.ADSyncPlatform.ActiveDirectory.Access
{
    /// <summary>
    /// 连接到AD
    /// </summary>
    public class ADConnection : IDisposable
    {

        /// <summary>
        /// AD的LDAP地址
        /// </summary>
        public string LDAPPath { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 连接的AD对象
        /// </summary>
        internal DirectoryEntry RootEntry
        {
            get;
            set;
        }

        public string RootPath
        {
            get
            {

                string[] paths = this.LDAPPath.Split("/");
                if (!this.LDAPPath.StartsWith("LDAP://"))
                {
                    return "LDAP://" + paths[0];
                }
                else
                {
                    return "LDAP://" + paths[2];
                }
            }
        }
        public ADConnection() { }
        /// <summary>
        /// 构造连接对象
        /// </summary>
        /// <param name="ldapPath">AD的LDAP地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="adcInfo">连接AD的基础信息</param>
        /// <param name="searchLocation">查询位置，默认GC</param>
        internal ADConnection(string ldapPath, string userName, string password)
        {
            this.LDAPPath = ldapPath;
            this.UserName = userName;
            this.Password = password;
            string ladp = GetLDAP(ldapPath);
            RootEntry = new DirectoryEntry(ladp, userName, password);
            try
            {
                Guid guid = RootEntry.Guid;
            }
            catch (Exception ex)
            {
                Dispose();
                RootEntry = null;
                throw ex;

                //throw new Exception($"无法获取路径【{ladp}】入口。");
            }

        }

        /// <summary>
        /// 关闭连接、释放资源
        /// </summary>
        public void Dispose()
        {
            if (RootEntry != null)
            {
                RootEntry.Close();
                RootEntry.Dispose();
            }
        }
        private string GetLDAP(string path)
        {
            //hack：未考虑path是否包含协议头
            if (path.Contains("://"))
            {
                return path;
            }
            return "LDAP://" + path;

        }
    }
}
